package com.dyzx.hbb.modules.wms.controller;


import cn.hutool.core.bean.BeanUtil;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.common.config.MyLambdaQueryWrapper;
import com.dyzx.hbb.common.controller.BaseValidController;
import com.dyzx.hbb.common.utils.Utils;
import com.dyzx.hbb.modules.wms.entity.WmsInventory;
import com.dyzx.hbb.modules.wms.entity.WmsStockOutDetails;
import com.dyzx.hbb.modules.wms.entity.WmsStockOutOrders;
import com.dyzx.hbb.modules.wms.query.WmsStockOutOrdersQuery;
import com.dyzx.hbb.modules.wms.service.WmsInventoryService;
import com.dyzx.hbb.modules.wms.service.WmsStockOutDetailsService;
import com.dyzx.hbb.modules.wms.service.WmsStockOutOrdersService;
import com.dyzx.hbb.modules.wms.vo.WmsStockOutDetailsVO;
import com.dyzx.hbb.modules.wms.vo.WmsStockOutOrdersStatusUVO;
import com.dyzx.hbb.modules.wms.vo.WmsStockOutOrdersUVO;
import com.dyzx.hbb.modules.wms.vo.WmsStockOutOrdersVO;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 出库单管理控制器
 * <p>处理仓库管理系统中出库单的创建、查询和状态管理等业务逻辑
 * <p>主要职责：
 * <ul>
 * <li>提供出库单的创建接口</li>
 * <li>支持按条件查询出库单列表</li>
 * <li>处理出库单与商品明细的关联</li>
 * <li>实现库存数量的减少操作</li>
 * <li>管理出库单的多状态流转（审核、拒绝、取消、作废、出口完成）</li>
 * </ul>
 * <p>设计意图：为仓库管理模块提供标准化的出库流程管理，
 * 确保出库操作的可追踪性和库存数据的准确性
 * 
 * @author 开发团队
 * @version 1.0.0
 * @since 2023-05-30
 */
@Tag(name = "出库单管理", description = "出库单相关接口")
@RestController
@RequestMapping("/wms/stock/out/orders")
public class WmsStockOutOrdersController extends BaseValidController<
        WmsStockOutOrdersService,
        WmsStockOutOrders,
        WmsStockOutOrdersQuery,
        WmsStockOutOrdersVO,
        WmsStockOutOrdersUVO
        > {

    @Autowired
    private WmsStockOutOrdersService service;


    @Autowired
    private WmsInventoryService inventoryService;

    @Autowired
    private WmsStockOutDetailsService detailsService;

    @Override

    protected WmsStockOutOrdersService getBaseService() {
        return service;
    }

    @Override
    protected MyLambdaQueryWrapper<WmsStockOutOrders> queryWrapper(WmsStockOutOrdersQuery query) {
        MyLambdaQueryWrapper<WmsStockOutOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(WmsStockOutOrders::getId)
                .select(WmsStockOutOrders::getNo)
                .houseName(WmsStockOutOrders::getHouseId).as("house_name")
             //   .houseLeaderName(WmsStockOutOrders::getHouseId).as("house_leader_name")
                .userName(WmsStockOutOrders::getSalesmanId).as("salesman_name")
                .userName(WmsStockOutOrders::getAuditorId).as("auditor_name")
                .userName(WmsStockOutOrders::getExporterId).as("exporter_name")
                .select(WmsStockOutOrders::getStatus)
                .select(WmsStockOutOrders::getCreateDate)
                .select(WmsStockOutOrders::getUpdateDate)
                .select(WmsStockOutOrders::getOperatorId)
                .select(WmsStockOutOrders::getQuantity)
        .organName(WmsStockOutOrders::getOrganId).as("organ_name")
                .select(WmsStockOutOrders::getPrice);
        queryWrapper.orderByDesc(WmsStockOutOrders::getCreateDate);

        if (query != null) {
            queryWrapper.likeRight(query.getNo() != null, WmsStockOutOrders::getNo, query.getNo())
                    .eq(query.getStatus()>0, WmsStockOutOrders::getStatus, query.getStatus())
                    .eq(query.getHouse_id() != null, WmsStockOutOrders::getHouseId, query.getHouse_id())
                    .eq(query.getLocation_id() != null, WmsStockOutOrders::getLocationId, query.getLocation_id())
                    .eq(query.getLocation_area_id() != null, WmsStockOutOrders::getLocationAreaId, query.getLocation_area_id());
        }
        return queryWrapper;
    }

    @Override
    protected MyLambdaQueryWrapper<WmsStockOutOrders> queryInfoWrapper() {
        MyLambdaQueryWrapper<WmsStockOutOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(WmsStockOutOrders::getId)
                .select(WmsStockOutOrders::getNo)
                .houseName(WmsStockOutOrders::getHouseId).as("house_name")
                .houseLeaderName(WmsStockOutOrders::getHouseId).as("house_leader_name")
                .userName(WmsStockOutOrders::getSalesmanId).as("salesman_name")
                .userName(WmsStockOutOrders::getAuditorId).as("auditor_name")
                .userName(WmsStockOutOrders::getExporterId).as("exporter_name")
                .select(WmsStockOutOrders::getStatus)
                .select(WmsStockOutOrders::getCreateDate)
                .select(WmsStockOutOrders::getUpdateDate)
                .select(WmsStockOutOrders::getOperatorId)
                .select(WmsStockOutOrders::getQuantity)
                .select(WmsStockOutOrders::getPrice);

        queryWrapper.orderByDesc(WmsStockOutOrders::getCreateDate);
        return queryWrapper;
    }

    @Override
    protected WmsStockOutOrders addValid(WmsStockOutOrdersVO entity) {
        return null;
    }

    @Override
    protected WmsStockOutOrders editValid(WmsStockOutOrdersUVO entity) {
        return null;
    }

    /**
     * 新增
     */
    @Operation(summary = "新增")
    @PostMapping
    public Result<Boolean> save(@Valid @RequestBody WmsStockOutOrdersVO entity) {
        if (entity == null) {
            return Result.error("参数不能为空");
        }

        WmsStockOutOrders entityCopy = new WmsStockOutOrders();
        BeanUtil.copyProperties(entity, entityCopy);
        if (entityCopy == null) {
            return Result.error("创建实体对象失败");
        }

        List<WmsStockOutDetailsVO> details = entity.getDetails();

 /*       Class<?> aClass = entityCopy.getClass();
        // 方案二：检查字段存在性（需要时使用）
        boolean hasOrganField = Arrays.stream(aClass.getDeclaredFields())
                .anyMatch(f -> ORGAN_FIELD.equals(f.getName()));
        boolean hasOperatorField = Arrays.stream(aClass.getDeclaredFields())
                .anyMatch(f -> OPRERATOR_FIELD.equals(f.getName()));
        Long userId = SecurityContextHolder.getUserId();
        if(hasOperatorField) {
            BeanUtil.setProperty(entityCopy, OPRERATOR_FIELD, userId);

        }

        if(hasOrganField){
            Long organId = SecurityContextHolder.getOrganId();
            BeanUtil.setProperty(entityCopy, ORGAN_FIELD, organId);

        }
*/
        Long userId = SecurityContextHolder.getUserId();
        entityCopy.setOperatorId(userId);
        entityCopy.setSalesmanId(userId);
        Long organId = SecurityContextHolder.getOrganId();
        entityCopy.setOrganId(organId);
        String s = Utils.generateYyMMOrderNumber("OUT");
        entityCopy.setNo(s);

        boolean save = getBaseService().save(entityCopy);
        if (save) {
            if (details != null && !details.isEmpty()) {
                List<WmsStockOutDetails> wmsStockInDetails = new ArrayList<>();

                for (WmsStockOutDetailsVO detail : details) {


                    WmsStockOutDetails item = new WmsStockOutDetails();

                    BeanUtil.copyProperties(detail, item);
                    //  item.setUniPrice((detail.getUniPrice()*100));
                    item.setOrderId(entityCopy.getId());
                    item.setOperatorId(userId);
                    item.setOrganId(organId);
                    WmsInventory inventory = inventoryService.getInventory(item);
                    item.setInventoryId(inventory.getId());
                    item.setHouseId(inventory.getHouseId());
                    item.setLocationId(inventory.getLocationId());
                    item.setLocationAreaId(inventory.getLocationAreaId());
                    //   WmsInventory inventory = inventoryService.getInventory(detail);
                    wmsStockInDetails.add(item);
                }
                boolean b = detailsService.saveBatch(wmsStockInDetails);
                if (b) {

                    return Result.ok();
                } else {
                    return Result.error("保存失败");
                }
            }
        }
        return save ? Result.ok() : Result.error("保存失败");
    }

    //已审核人员编号，出口人员编号
    @Operation(summary = "审核")
    @PutMapping("/status")
    public Result<Boolean> updateStatus(@RequestBody WmsStockOutOrdersStatusUVO param)  {
        int status = param.getStatus();
        Long id = param.getId();
        if (id == null || status<=0) {
            return Result.error("参数不能为空");
        }
        WmsStockOutOrders entity = getBaseService().getById(id);
        if (entity == null) {
            return Result.error("参数错误");
        }
        Long userId = SecurityContextHolder.getUserId();
        Long organId = SecurityContextHolder.getOrganId();
        if (!Objects.equals(entity.getOrganId(), organId)) {
            return Result.error("找不到该仓库");
        }
        // 审核状态: 1:待审核 2:审核通过 3:审核拒绝 4:取消审核 5:作废 10:出口完成
        switch (status) {
           /* case 1:
                entity.setStatus(1);
                break;*/
            //...
            case 2:
                entity.setStatus(2);
                entity.setAuditorId(userId);
                break;
            case 3:
                entity.setStatus(3);
                break;
            case 4:
                entity.setStatus(4);
                break;
            case 5:
                entity.setStatus(5);
                break;
            case 10:
                entity.setStatus(10);
                entity.setExporterId(userId);
                break;
            default:
                return Result.error("参数错误");
        }
        boolean b = getBaseService().updateById(entity);
        return b ? Result.ok() : Result.error("审核失败");
    }
}